<template>
    <div class="w-[55%] mx-auto ">
        <div class="frame-bg">
            <a-form auto-label-width :model="formData" ref="formRef" :rules="rules">
                <a-form-item label="唯一标识" field="name" validate-trigger="blur">
                    <a-input v-model="formData.name" />
                </a-form-item>

                <a-form-item label="名称" field="title" validate-trigger="blur">
                    <a-input v-model="formData.title" />
                </a-form-item>
                <a-row>
                    <a-col :span="12">
                        <a-form-item label="所属标签" field="setting_id" validate-trigger="blur">
                            <a-input v-model="formData.setting_id" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="类型" field="type" validate-trigger="blur">
                            <a-select v-model="formData.type" @change="changeType" :options="typeList" />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-form-item label="值" field="value" validate-trigger="blur" v-if="formData.type !== 'select'">
                    <a-input v-if="formData.type === 'text'" v-model="formData.value" />
                    <a-input-number v-if="formData.type === 'number'" v-model="formData.value" />
                    <a-switch v-if="formData.type === 'boolean'" v-model="formData.value" />
                    <a-textarea v-if="formData.type === 'custom'" v-model="formData.value" />
                </a-form-item>

                <a-form-item v-else v-for="(item, index) in formData.value" :key="index" :label="index === 0 ? '选项' : ''"
                    :field="`value.${index}`" validate-trigger="blur">
                    <div class="flex items-center gap-2">
                        
                        <a-input v-model="item.key" placeholder="键名" />
                        <a-input v-model="item.value" placeholder="键值" />
                        <a-button type="primary" @click="addSelect">添加</a-button>
                        <a-button type="primary" :disabled="index === 0" @click="deleteSelect(index)">删除</a-button>
                    </div>
                </a-form-item>

                <a-form-item class="main-bottom">
                    <a-button type="primary" @click="handleSubmit">提交</a-button>
                    <a-button @click="handleReset">重置</a-button>
                </a-form-item>
            </a-form>

            {{ formData }}
        </div>
    </div>
</template>

<script setup lang="ts">

const formRef = ref()

const typeList = [
    {
        label: '文本',
        value: 'text'
    },
    {
        label: '数字',
        value: 'number'
    },
    {
        label: '布尔',
        value: 'boolean'
    },
    {
        label: '下拉表单',
        value: 'select',
    },
    {
        label: '自定义',
        value: 'custom',
    }
]

interface FormData {
    name: string
    title: string
    setting_id: string
    type: 'text' | 'number' | 'boolean' | 'select' | 'custom'
    value: any
}

const formData = reactive<FormData>({
    name: '',
    title: '',
    setting_id: '',
    type: 'text',
    value: ''
})

const formatJson = (value: string) => {
    // 如果是空值，直接返回
    if (!value || value.trim() === '') {
        return ''
    }

    // 移除首尾空白
    const trimmed = value.trim()

    // 如果不是以 [ 或 { 开头，则视为普通字符串
    if (!trimmed.startsWith('[') && !trimmed.startsWith('{')) {
        return trimmed
    }

    try {
        // 尝试解析为 JSON
        const parsed = JSON.parse(trimmed)
        return JSON.stringify(parsed)
    } catch (error) {
        // 如果解析失败，尝试格式化
        if (trimmed.startsWith('[')) {
            // 处理数组格式
            const items = trimmed
                .replace(/^\[|\]$/g, '') // 移除开头和结尾的中括号
                .split('\n') // 按行分割
                .map(item => item.trim()) // 移除每行的空白
                .filter(item => item && !item.match(/^[\[\],]*$/)) // 移除空行和只包含 [,] 的行
                .map(item => {
                    // 如果是键值对格式（包含:），转换为对象
                    if (item.includes(':')) {
                        const [key, val] = item.split(':').map(s => s.trim())
                        return `{"${key.replace(/^"|"$/g, '')}":"${val.replace(/^"|"$/g, '')}"}`
                    }
                    // 如果是单个值，保持原样
                    return item.includes('{') ? item : `"${item.replace(/^"|"$/g, '')}"`
                })
            return `[${items.join(',')}]`
        } else if (trimmed.startsWith('{')) {
            // 处理对象格式
            const items = trimmed
                .replace(/^{|}$/g, '') // 移除开头和结尾的大括号
                .split('\n') // 按行分割
                .map(item => item.trim()) // 移除每行的空白
                .filter(item => item && !item.match(/^[{},]*$/)) // 移除空行和只包含 {,} 的行
                .map(item => {
                    if (item.includes(':')) {
                        const [key, val] = item.split(':').map(s => s.trim())
                        return `"${key.replace(/^"|"$/g, '')}":${val.includes('{') || val.includes('[') ? val : `"${val.replace(/^"|"$/g, '')}"`}`
                    }
                    return item
                })
            return `{${items.join(',')}}`
        }
        return value
    }
}

const validateJson = (value: string) => {
    if (!value || value.trim() === '') {
        return '请输入值'
    }

    // 如果不是以 [ 或 { 开头，则视为普通字符串，直接通过验证
    if (!value.trim().startsWith('[') && !value.trim().startsWith('{')) {
        return true
    }

    try {
        // 尝试解析
        JSON.parse(value)
        return true
    } catch (error) {
        return 'JSON 格式错误，' + (error as Error).message
    }
}

const rules = {
    name: [
        { required: true, message: '请输入唯一标识', trigger: 'blur' },
        { minLength: 2, message: '唯一标识至少2个字符', trigger: 'blur' }
    ],
    title: [
        { required: true, message: '请输入名称', trigger: 'blur' },
        { minLength: 2, message: '名称至少2个字符', trigger: 'blur' }
    ],
    setting_id: [
        { required: true, message: '请输入所属标签', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择类型', trigger: 'blur' }
    ],
    value: [
        { required: true, message: '请输入值', trigger: 'blur' },
        { 
            validator: (value: string, callback: (error?: string) => void) => {
                const result = validateJson(value)
                if (result === true) {
                    callback()
                } else {
                    callback(result)
                }
            },
            trigger: 'blur'
        }
    ]
}

const changeType = (value: string) => {
    switch (value) {
        case 'select':
            formData.value = [{ key: '', value: '' }]
            break
        default:
            formData.value = ''
            break
    }
}

const addSelect = () => {
    formData.value.push({ key: '', value: '' })
}

const deleteSelect = (index: number) => {
    if (formData.value.length > 1) {
        formData.value.splice(index, 1)
    }
}

const handleSubmit = async () => {
    try {
        const res = await formRef.value?.validate()
        if (res) {
            return
        }

        // 创建一个新的对象，而不是直接使用 formData
        const SubmitData = {
            ...formData,
            value: formData.type === 'custom' ? formatJson(formData.value) : formData.value
        }

        if (SubmitData.type === 'custom') {
            try {
                // 如果是 JSON 格式，尝试解析
                if (SubmitData.value.startsWith('[') || SubmitData.value.startsWith('{')) {
                    SubmitData.value = JSON.parse(SubmitData.value)
                }
                // TODO: 这里添加提交逻辑
            } catch (error) {
                return
            }
        }
        console.log('提交的数据:', SubmitData)
    } catch (err: any) {
        return
    }
}

const handleReset = () => {
    formRef.value?.resetFields()
    formData.value = ''
}
</script>

<style scoped lang="scss">
.frame-bg {
    padding: 40px;
    border-radius: 20px;
    background: var(--color-fill-2);

    .arco-form {
        border-radius: 10px;
        padding: 20px !important;
        background-color: var(--color-bg-2);
        margin-top: 20px !important;
    }
}

.main-bottom {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    button {
        margin: 0 20px;
    }
}
</style>